const Service = require('egg').Service;
module.exports = class Active extends Service {
  async platformPize(params) {
    const { ctx, service } = this;
    let res = {}, { type, page, pageSize, prizeId } = params, limit = [(page - 1) * pageSize, pageSize]
    try {
      // let where, res = {}
      if (type == 3) {
        let str = ` is_valid=1 `
        str = prizeId ? `${str} AND couponid = ${prizeId}` : str;
        // str = ` ${str} ORDER BY c_time DESC LIMIT ${limit.join(',')}`;
        res.list = await service.common.findAll({
          tableName: 'tb_coupon',
          filed: ['couponid as id', 'productid', 'coupon_name as name', 'coupon_type as prizeType', 'coupon_rate', 'coupon_rate_days as rate_days', 'valid_days', 'coupon_total as totalNum', 'coupon_send as sendNum', `DATE_FORMAT(send_time_start,'%Y/%m/%d:%H:%i:%S') as start_time`, `DATE_FORMAT(send_time_end,'%Y/%m/%d:%H:%i:%S') as end_time`, 'c_by', 'u_by', `DATE_FORMAT(c_time,'%Y/%m/%d:%H:%i:%S') as create_time`, `DATE_FORMAT(u_time,'%Y/%m/%d:%H:%i:%S') as update_time`],
          where: ` ${str} ORDER BY c_time DESC LIMIT ${limit.join(',')}`,
          model: 'appModel'
        })

        res.total = (await service.common.findOne({
          tableName: 'tb_coupon',
          filed: ['count(*) as totalNum'],
          where: str,
          model: 'appModel'
        })).totalNum
      } else if (type == 2 || type == 1) {
        let str = ` is_valid=1 AND rpcfg_type=${{ 1: 22, 2: 21 }[type]}`
        str = prizeId ? `${str} AND rpcfgid = ${prizeId}` : str;
        // str = ` ${str} ORDER BY c_time DESC LIMIT ${limit.join(',')}`;
        res.list = await service.common.findAll({
          tableName: 'tb_red_packet_cfg',
          filed: ['rpcfgid as id', 'rpcfg_name as name', 'rpcfg_type as prizeType', 'rpcfg_rate_days as rate_days', 'money_mode', 'rpcfg_total as totalNum', 'rpcfg_send as sendNum', 'c_by', 'u_by', `DATE_FORMAT(c_time,'%Y/%m/%d:%H:%i:%S') as create_time`, `DATE_FORMAT(u_time,'%Y/%m/%d:%H:%i:%S') as update_time`],
          where: ` ${str} ORDER BY c_time DESC LIMIT ${limit.join(',')}`,
          model: 'appModel'
        })
        // 查询总数
        res.total = (await service.common.findOne({
          tableName: 'tb_red_packet_cfg',
          filed: ['count(*) as totalNum'],
          where: str,
          model: 'appModel'
        })).totalNum
      }


      return {
        code: 10200,
        data: res,
        msg: 'success'

      }
    } catch (error) {

      return {
        code: 10500,
        msg: '查询报错'
      }
    }

  }
  async selfCreatePrize(params) {
    const { ctx, service } = this;
    let res = {}, { type, page, pageSize, prizeId, name } = params, limit = [(page - 1) * pageSize, pageSize]
    try {
      let where = [` status=1 AND type=${type}`];
      prizeId ? where.push(`AND id = ${prizeId}`) : '';
      name ? where.push(`AND id = ${prizeId}`) : '';

      // let str = ` status=1 AND type=${type}`
      // str = prizeId ? `${str} AND id = ${prizeId}` : str;

      // str = ` ${str} ORDER BY create_time DESC LIMIT ${limit.join(',')}`;
      res.list = await service.common.findAll({
        tableName: 'hd_award_config',
        where: `${where.join(' ')}  ORDER BY create_time DESC LIMIT ${limit.join(',')}`,
        filed: ['id', 'type', 'name', 'total', 'receive_url', 'url', 'blocked_stock', 'unit_price', 'total_price', 'send_out', 'use_out', `DATE_FORMAT(create_time,'%Y/%m/%d %H:%i:%S') as c_time `, `DATE_FORMAT(update_time,'%Y/%m/%d %H:%i:%S') as u_time`, `DATE_FORMAT(start_time,'%Y/%m/%d %H:%i:%S') as start_time`, `DATE_FORMAT(end_time,'%Y/%m/%d %H:%i:%S') as end_time`]
      })
      res.total = (await service.common.findOne({
        tableName: 'hd_award_config',
        filed: ['count(*) as totalNum'],
        where: `${where.join(' ')}`
      })).totalNum

      return {
        code: 10200,
        data: res,
        msg: 'success'
      }
    } catch (error) {
      console.log(error);
      return {
        code: 10500,
        msg: '系统异常'
      }
    }
  }
  /**
   * 删除自建奖品
   */
  async DelselfCreatePrize({ userId, prizeId }) {
    const { ctx, service, logger } = this;
    try {
      let res = await service.common.upData({
        tableName: 'hd_award_config',
        value: {
          status: 2
        },
        where: {
          id: prizeId
        }
      })
      return res ? { code: 10200, msg: "删除成功" } : { code: 10201, msg: '删除失败' }
    } catch (error) {

      logger.info('自建奖品删除失败');
      return {
        code: 10500,
        msg: '系统错误'
      }
    }

  }

  /**
   * 添加自建奖品
   */
  async AddselfCreatePrize(params) {
    const { ctx, service, logger } = this;
    let { url, department, type, name, start_time, end_time, total, unit_price, receive_method, total_price, purchase, receive_url } = params;
    try {
      let params = {
        url: `'${url}'`,
        department,
        type,
        name: `'${name}'`,
        start_time: `'${start_time}'`,
        end_time: `'${end_time}'`,
        total,
        unit_price,
        receive_method,
        purchase: `'${purchase}'`,
        receive_url: `'${receive_url}'`,
        total_price
      }
      for (let key in params) {
        if (!params[key]) {
          delete params[key]
        }
      };
      let res = await service.common.insertOne({
        tableName: 'hd_award_config',
        params
      })
      return res ? { code: 10200, msg: "创建成功" } : { code: 10201, msg: '创建失败' }
    } catch (error) {

      logger.info('自建奖品创建失败');
      return {
        code: 10500,
        msg: '系统错误'
      }
    }

  }

  /**
   * 更新自建奖品
   */
  async modifySelfCreatePrize(params) {
    const { ctx, service, logger } = this;
    let { prizeId, department, end_time, url, total, receive_method, purchase, operationType, total_price, unit_price, receive_url } = params;
    try {
      let params = operationType !== 'del' ? {
        department,
        end_time: `'${end_time}'`,
        total,
        url: `'${url}'`,
        unit_price,
        receive_method,
        purchase: `'${purchase}'`,
        total_price,
        receive_url: `'${receive_url}'`
      } : {
          status: 2
        }
      // let params = {
      //   department,
      //   end_time: `'${end_time}'`,
      //   total,
      //   unit_price,
      //   receive_method,
      //   purchase: `'${purchase}'`,
      //   blocked_stock,
      //   total_price
      // }
      for (let key in params) {
        if (!params[key]) {
          delete params[key]
        }
      };
      let res = await service.common.upData({
        tableName: 'hd_award_config',
        value: params,
        where: {
          id: prizeId
        }
      })
      return res ? { code: 10200, msg: "操作成功" } : { code: 10201, msg: '操作失败' }
    } catch (error) {
      console.log(error)
      logger.info('自建奖品更新失败');
      return {
        code: 10500,
        msg: '系统错误'
      }
    }

  }

  /**
   * 新建活动
   */
  async addActive(params) {
    const { ctx, service, logger, app } = this;
    let { userId, schedule, department, name, start_time, end_time, background_image_url, activity_abroad_url, is_use_coupon, goods_restrictions, channels, is_old_data } = params;
    try {

      channels = JSON.parse(channels)
      if (channels.length < 1) {
        return {
          code: 10201,
          msg: "channels不能为空"
        }
      }

      let activeName = await service.common.findOne({
        tableName: 'hd_activity_base',
        filed: ['name'],
        where: { name: `'${name}'` }
      })
      console.log('%c gc_activeName=>: ', 'color: MidnightBlue; background: Aquamarine; font-size: 20px;', activeName);
      if (activeName && activeName.name) { // 活动名称去重
        return {
          code: 10201,
          msg: '活动名称已经存在，请重新输入'
        }
      }

      // 查询管理员账号
      let userInfo = await service.common.findOne({
        tableName: 'hd_admin_user',
        where: {
          auserid: userId
        }
      })
      if (!userInfo.account_name) {
        return {
          code: 10201,
          msg: "没有权限操作"
        }
      }
      let params = {
        schedule,
        admin_id: userInfo.account_name,
        department,
        name: `'${name}'`,
        start_time: `'${start_time}'`,
        end_time: `'${end_time}'`,
        show_content: `'pipizhu'`,
        background_image_url: `'${background_image_url}'`,
        activity_abroad_url: `'${activity_abroad_url}'`,
        goods_restrictions: `'${goods_restrictions}'`,
        activity_rule: `''`,
        is_old_data: is_old_data || 1,
        event_key: Math.random(),
        is_use_coupon,
        participation_restrictions: `''`,
      }
      // for (let key in params) {
      //   if (!params[key]) {
      //     delete params[key]
      //   }
      // };
      let res = await service.common.insertOne({
        tableName: 'hd_activity_base',
        params
      })
      let activeId = res[0];
      // 更新活动标识
      let event_key = ctx.helper.getEventKey(activeId, Date.now(), 'H');

      await service.common.upData({
        tableName: 'hd_activity_base',
        value: {
          event_key: `'${event_key}'`,
        },
        where: {
          id: activeId
        }
      })
      // 生成渠道
      channels = await service.admin.active.createChannel(channels);
      // 生成渠道关系表
      let _channels = await service.admin.active.createRelation(activeId, channels);

      // 奖品信息保存到redis中
      let activeInfo = await service.common.findOne({
        tableName: 'hd_activity_base',
        where: {
          id: activeId
        }
      })
      let redisKey = `${app.config.redisKey.activeBaseInfo}:${activeId}`
      activeInfo.start_time = ctx.helper.formDate(new Date(activeInfo.start_time), 'YYYY-MM-DD HH:mm:ss')
      activeInfo.end_time = ctx.helper.formDate(new Date(activeInfo.end_time), 'YYYY-MM-DD HH:mm:ss')
      // for (let key in activeInfo) {
      await app.redis.hmset(redisKey, activeInfo);
      // }

      // if (is_old_data == 3) {
      //   return {
      //     code: 10200,
      //     msg: '创建成功'
      //   }
      // }
      return is_old_data == 3 ? _channels : { code: 10200, msg: "创建成功" }
    } catch (error) {

      // logger.info('自建奖品创建失败');
      console.log('error', error)
      return is_old_data == 3 ? null : { code: 10500, msg: "系统错误" }
      // return {
      //   code: 10500,
      //   msg: '系统错误'
      // }
    }

  }

  /**
   * 编辑活动
   */
  async editActive(params) {
    const { ctx, service, logger, app } = this;
    let { userId, activeId, end_time, background_image_url, activity_abroad_url, is_use_coupon, goods_restrictions, channels, status, cash_red_packet_ids, experience_red_packet_ids, award_ids, coupon_ids, activity_rule } = params;
    try {
      // console.log('%c gc_status=>: ','color: MidnightBlue; background: Aquamarine; font-size: 20px;',status);
      // if(operationType==='del'){ //删除活动
      // }
      channels = channels ? JSON.parse(channels) : channels
      let params = {
        admin_id: userId,
        end_time: end_time ? `'${end_time}'` : null,
        background_image_url: background_image_url ? `'${background_image_url}'` : null,
        activity_abroad_url: activity_abroad_url ? `'${activity_abroad_url}'` : null,
        goods_restrictions: goods_restrictions ? `'${goods_restrictions}'` : '',
        is_use_coupon,
        cash_red_packet_ids: cash_red_packet_ids ? `'${cash_red_packet_ids}'` : null,
        experience_red_packet_ids: experience_red_packet_ids ? `'${experience_red_packet_ids}'` : null,
        award_ids: award_ids ? `'${award_ids}'` : null,
        coupon_ids: coupon_ids ? `'${coupon_ids}'` : null,
        activity_rule: activity_rule ? `'${activity_rule}'` : null,
        status: status || null
      }
      console.log(params, 'params--------------params')
      // 删除空的key
      for (let key in params) {
        if (!params[key]) {
          delete params[key]
        }
      };

      await service.common.upData({
        tableName: 'hd_activity_base',
        value: params,
        where: {
          id: activeId
        }
      })

      // 生成渠道

      if (channels && channels.length > 0) {
        channels = await service.admin.active.createChannel(channels);
      }
      if (channels && channels.length > 0 || end_time) {
        // 生成渠道关系id
        await service.admin.active.createRelation(activeId, channels);
      }

      // 奖品信息保存到redis中
      await service.admin.active._saveActiveInfoRedis(activeId)
      // }

      return {
        code: 10200,
        msg: '更新成功'
      }
    } catch (error) {
      console.log(error, 'error')
      logger.info('活动更新失败');
      return {
        code: 10500,
        msg: '系统错误'
      }
    }

  }


  /**
   *
   * @param {*} activeId  活动id
   */
  async _saveActiveInfoRedis(activeId) {
    // 奖品信息保存到redis中
    const { app, service, ctx } = this;
    let activeInfo = await service.common.findOne({
      tableName: 'hd_activity_base',
      where: {
        id: activeId
      }
    })
    let redisKey = `${app.config.redisKey.activeBaseInfo}:${activeId}`
    activeInfo.start_time = ctx.helper.formDate(new Date(activeInfo.start_time), 'YYYY-MM-DD HH:mm:ss')
    activeInfo.end_time = ctx.helper.formDate(new Date(activeInfo.end_time), 'YYYY-MM-DD HH:mm:ss')
    // for (let key in activeInfo) {
    let res = {
      'nonstandardActivityAward': activeInfo.activity_rule,
      'getRewards': []
    }
    await app.redis.hmset(redisKey, activeInfo);
    let prizeRulesKey = `${app.config.redisKey.prizeRules}:${activeId}`
    // 将活动规则保存到redis中
    if (res.nonstandardActivityAward) {
      // if()
      let rules = JSON.parse(res.nonstandardActivityAward);
      if (rules instanceof Array) {
        rules.forEach((item, index) => {
          if (item.result.getReward instanceof Array) {
            res.getRewards = res.getRewards.concat(item.result.getReward)
          }
        })
        res.getRewards = JSON.stringify(res.getRewards)
        await app.redis.hmset(prizeRulesKey, res);

      }

    }

  }

  /**
   * 获取活动列表
   * @param {*} userId  用户id
   */
  async getActiveList({ userId, pageSize, page, schedule, name, id, is_old_data }) {
    const { ctx, service, logger, app } = this;
    let limit = [(page - 1) * pageSize, pageSize], res = {};
    try {
      let where = [` status<4 AND is_old_data=${is_old_data || 1}`]
      // if(id){
      id ? where.push(`AND id=${id}`) : ''
      schedule ? where.push(`AND schedule=${schedule} `) : ''
      name ? where.push(`AND name='${name}' `) : ''

      // }
      res.list = await service.common.findAll({
        tableName: 'hd_activity_base',
        filed: ['id', 'name', 'department', 'activity_rule', 'activity_abroad_url', 'goods_restrictions', 'schedule', 'event_key', 'is_use_coupon', 'coupon_ids', 'award_ids', 'cash_red_packet_ids', 'experience_red_packet_ids', `DATE_FORMAT(start_time,'%Y/%m/%d:%H:%i:%S') as start_time`, `DATE_FORMAT(end_time,'%Y/%m/%d:%H:%i:%S') as end_time`, `DATE_FORMAT(update_time,'%Y/%m/%d:%H:%i:%S') as u_time`, `DATE_FORMAT(create_time,'%Y/%m/%d:%H:%i:%S') as c_time`, 'admin_id'],
        where: `${where.join(' ')} ORDER BY create_time DESC LIMIT ${limit.join(',')}`
      })

      res.total = (await service.common.findOne({
        tableName: 'hd_activity_base',
        filed: ['count(*) as num'],
        where: `${where.join(' ')}`
      })).num;
      return {
        code: 10200,
        data: res,
        msg: 'success',
      }
      // console.log('%c gc_activeList=>: ', 'color: MidnightBlue; background: Aquamarine; font-size: 20px;', activeList);

    } catch (error) {
      console.log(error);
      return {
        code: 10500,
        msg: '获取活动列表失败'
      }
    }

  }

  /**
   * 渠道入库
   * @param {*} channels
   */
  async createChannel(channels) {
    let { ctx, service } = this
    // channels.forEach(item => {

    for (let item of channels) {
      let params

      if (item.id) { // 更新
        item.name ? await ctx.service.common.upData({
          tableName: 'hd_channel',
          value: {
            name: `'${item.name}'`,
          },
          where: {
            id: item.id
          }
        }) : ''
        item.sign = 'update'
      } else { // 插入
        params = {
          name: `'${item.name}'`,
          hb_type: `'${Math.random().toString(32)}'`
        }
        let res = await service.common.insertOne({
          tableName: 'hd_channel',
          params
        })
        if (!res[0]) {
          throw new Error('渠道关系id插入失败')
        }
        item.chanelId = res[0];
        let hb_type = ctx.helper.getEventKey(res[0], Date.now(), 'Q');
        await service.common.upData({
          tableName: 'hd_channel',
          value: {
            hb_type: `'${hb_type}'`,
          },
          where: {
            id: res[0]
          }
        })

      }
    }
    return channels
    // });
  }

  /**
   *
   * @param {*} activeId 活动id
   * @param {*} channels 渠道信息
   */
  async createRelation(activeId, channels) {
    const { ctx, service } = this;
    for (let item of channels) {
      if (item.sign === 'update' && item.value[1]) { // 更新
        await ctx.service.common.upData({
          tableName: 'hd_combination_relation',
          value: {
            end_time: `'${item.value[1]}'`
          },
          where: {
            channel_id: item.id,
            activity_id: activeId
          }
        })
      } else {// 插入
        let params = {
          activity_id: activeId,
          channel_id: item.chanelId,
          start_time: `'${item.value[0]}'`,
          end_time: `'${item.value[1]}'`
        }
        let res = await service.common.insertOne({
          tableName: 'hd_combination_relation',
          params,
        })
        if (!res[0]) {
          throw new Error('渠道关系id插入失败');
        }
        item.combinationId = res[0]
      }
    }
    return channels
  }
  async getChannels(activeId) {
    let { ctx, service } = this;
    try {
      let res = await service.common.findAll({
        sql: `SELECT
        hc.id,
        hc.name,
        DATE_FORMAT(hcr.start_time,'%Y/%m/%d:%H:%i:%S') as start_time,
        DATE_FORMAT(hcr.end_time,'%Y/%m/%d:%H:%i:%S') as end_time
      FROM
        hd_combination_relation AS hcr
      LEFT JOIN hd_channel AS hc ON hcr.channel_id = hc.id
      WHERE
        hcr.activity_id = ${activeId}
      `})
      console.log(res, '-----------==>')
      return {
        code: 10200,
        data: res,
        msg: 'success'
      }
    } catch (error) {
      console.log(error)
    }
  }

  async getActiveLink(activeId) {
    const { ctx, service } = this;
    try {
      let res = await service.common.findAll({
        sql: `
        SELECT hab.activity_abroad_url as url ,hcr.id as combinationId ,hc.name,hab.is_use_coupon as isShowCoupon
        FROM hd_activity_base as hab
        LEFT JOIN hd_combination_relation as hcr on hab.id=hcr.activity_id
        LEFT JOIN hd_channel as hc on hcr.channel_id = hc.id
        WHERE activity_id=${activeId}
        `
      })
      res.forEach((item => {
        let _combination = item.combinationId ? ctx.helper.encryptCb(item.combinationId) : '';
        item.url = `${item.url}?combinationId=${_combination}&isShowCoupon=${item.isShowCoupon}`
      }))
      return {
        code: 10200,
        data: res,
        msg: "success"
      }
    } catch (error) {
      console.log(error);
      return {
        code: 10500,
        msg: '系统异常'
      }
    }

  }

  async getVirtualData({ combinationId }) {
    const { ctx, service, app } = this;
    try {
      let activeInfo = await service.common.findOne({
        tableName: 'hd_combination_relation',
        filed: ['activity_id'],
        where: {
          id: combinationId
        }
      })
      // console.log(activeInfo,'activeInfo----')
      let key, res = {};
      if (!activeInfo || !activeInfo.activity_id) {
        key = `${app.config.redisKey.redisVirtualDataKey}:${combinationId}`
        if (!await app.redis.exists(key)) {
          return {
            code: 10101,
            msg: "渠道关系id不存在",
            data: {}
          }
        }
      } else {
        key = `${app.config.redisKey.redisVirtualDataKey}:${activeInfo.activity_id}:${combinationId}`
      }

      let virtualData = await app.redis.hmget(key, ['nums', 'list']);
      res = virtualData.map((item) => {
        return JSON.parse(item)
      })

      return {
        msg: 'success',
        code: 10200,
        data: {
          nums: res[0] || [],
          list: res[1] || [],
          redisKey: key
        }
      }

    } catch (error) {
      console.log(error);
      return {
        code: 10500,
        msg: '系统错误'
      }
    }

  }

}